package test

/**
* @author aFun
* @data 2025/4/10 01:24
* @email: afunaaa222@163.com / 1030935903
* @address: Guangdong University of Technology, China
 */

import (
	"camp_lucky_draw/entity"
	"fmt"
	"github.com/jinzhu/gorm"
)

type CheckFunc func(role *entity.Role, Args map[string]interface{}) error

func Check(db *gorm.DB, role *entity.Role, Args map[string]interface{}) error {
	tx := db.Begin()
	if tx.Error != nil {
		return fmt.Errorf("tx.Error: %v", tx.Error)
	}

	err := do_check(
		role, Args,
		update_1,
		update_2)

	if err != nil {
		tx.Rollback()
		return err
	}

	// 执行更新
	// 使用Save可以保存所有字段
	if err := tx.Save(&role).Error; err != nil {
		tx.Rollback()
		return err
	}

	tx.Commit()

	tx.Commit()
	return err
}

func do_check(role *entity.Role, Args map[string]interface{}, checks ...CheckFunc) error {
	for _, check := range checks {
		if err := check(role, Args); err != nil {
			return err
		}
	}
	return nil
}

func update_1(role *entity.Role, Args map[string]interface{}) error {
	role.Asset = 0
	return nil
}

func update_2(role *entity.Role, Args map[string]interface{}) error {
	ld := role.Lucky_draw
	ld.Cur_floor = 3
	role.Lucky_draw = ld
	return nil
}
